package com.anysoft.utils.user;

import android.text.TextUtils;

import com.anysoft.bean.UserBean;
import com.anysoft.greenDAO.dao.UserBeanDao;
import com.anysoft.greenDAO.db.DbCore;
import com.anysoft.utils.StringUtils;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wwq on 2017/1/3.
 *
 */

public class UserBeanUtil {

    private static final String TAG = "UserBeanUtil";

    public static UserBeanDao mUserBeanDao;

    private static UserBeanUtil instance = null;

    private UserBeanUtil() {
        mUserBeanDao = DbCore.getDaoSession().getUserBeanDao();
    }

    public static UserBeanUtil getInstance() {
        if (instance == null) {
            instance = new UserBeanUtil();
        }
        return instance;
    }

    /**
     * 保存/更新
     *
     * @param userBean 用户对象
     */
    public static void saveUser(UserBean userBean) {
        UserBean mUserBean = mUserBeanDao.queryBuilder().where(UserBeanDao.Properties.UserId.eq(userBean.getUserId())).build().unique();
        if (mUserBean == null) {
            mUserBeanDao.insert(userBean);//添加到数据库
            Logger.t(TAG).d("数据添加成功" + userBean.toString());
        } else {
            if (!TextUtils.isEmpty(userBean.getUserName())) {
                mUserBean.setUserName(userBean.getUserName());
            }
            if (!TextUtils.isEmpty(userBean.getUserImgPath())) {
                mUserBean.setUserImgPath(userBean.getUserImgPath());
            }
            if (!TextUtils.isEmpty(userBean.getSex())) {
                mUserBean.setSex(userBean.getSex());
            }
            if (!TextUtils.isEmpty(userBean.getRecordIdentNumber())) {
                mUserBean.setRecordIdentNumber(userBean.getRecordIdentNumber());
            }
            mUserBean.setLastLoginTime(System.currentTimeMillis());
            mUserBeanDao.update(mUserBean);//更新数据库
            Logger.t(TAG).d("数据更新成功" + mUserBean.toString());
        }
    }

    /**
     * 查找
     */
    public static List<UserBean> findUserList() {
        List<UserBean> userList = new ArrayList<>();
        try {
            userList.addAll(mUserBeanDao.queryBuilder()
                    .where(UserBeanDao.Properties.Id.notEq(-1))
                    .orderAsc(UserBeanDao.Properties.Id)
//                .limit(5)
                    .build().list());
        } catch (Exception e) {
            Logger.t(TAG).d(e);
        }


        StringBuilder string = new StringBuilder("");
        for (int i = 0; i < userList.size(); i++) {
            string.append("\n" + userList.get(i).toString());
        }
        Logger.t(TAG).d(TextUtils.isEmpty(string.toString()) ? "暂无数据" : string.toString());
        return userList;
    }

    public static UserBean getUser(String userId) {
        UserBean userBean = mUserBeanDao.queryBuilder().where(UserBeanDao.Properties.UserId.eq(userId)).build().unique();

        if (userBean != null) {
            Logger.t(TAG).d("用户" + userId + "存在");
            return userBean;
        } else {
            Logger.t(TAG).d("用户不存在,id为" + userId);
            return null;
        }
    }

    public static String getUserType(String userId) {
        UserBean userBean = mUserBeanDao.queryBuilder().where(UserBeanDao.Properties.UserId.eq(userId)).build().unique();

        if (userBean != null) {
            Logger.t(TAG).d("用户" + userId + "类型为" + userBean.getUserType());
            return userBean.getUserType();
        } else {
            Logger.t(TAG).d("用户不存在,id为" + userId);
            return "";
        }
    }

    public static String getCustomerNo(String userId) {
        UserBean userBean = mUserBeanDao.queryBuilder().where(UserBeanDao.Properties.UserId.eq(userId)).build().unique();

        if (userBean != null) {
            Logger.t(TAG).d("用户" + userId + "CustomerNo为" + userBean.getFundCustomerNo());
            return userBean.getFundCustomerNo();
        } else {
            Logger.t(TAG).d("用户不存在,id为" + userId);
            return "";
        }
    }

    public static boolean isFingerPrintOpen(String userId) {
        UserBean userBean = mUserBeanDao.queryBuilder().where(UserBeanDao.Properties.UserId.eq(userId)).build().unique();

        if (userBean != null) {
            Logger.t(TAG).d("用户" + userId + "isFingerPrintOpen 指纹" + userBean.getIsFingerPrintOpen());
            return userBean.getIsFingerPrintOpen();
        } else {
            Logger.t(TAG).d("用户不存在,id为" + userId);
            return false;
        }
    }

    /**
     * 手势密码是否打开
     * @param userId
     * @return
     */
    public static boolean isGestureOpen(String userId) {
        UserBean userBean = mUserBeanDao.queryBuilder().where(UserBeanDao.Properties.UserId.eq(userId)).build().unique();

        if (userBean != null) {
            Logger.t(TAG).d("用户" + userId + "isGestureOpen 手势" + userBean.getIsGestureOpen());
            return userBean.getIsGestureOpen();
        } else {
            Logger.t(TAG).d("用户不存在,id为" + userId);
            return false;
        }
    }

    public static byte[] getSalt(String userId) {
        UserBean userBean = mUserBeanDao.queryBuilder().where(UserBeanDao.Properties.UserId.eq(userId)).build().unique();

        if (userBean != null) {
            Logger.t(TAG).d("用户" + userId + "盐为" + userBean.getGesture_salt());
            return userBean.getGesture_salt();
        } else {
            Logger.t(TAG).d("用户不存在,id为" + userId);
            return null;
        }
    }

    public static String getGestureRandomKey(String userId) {
        UserBean userBean = mUserBeanDao.queryBuilder().where(UserBeanDao.Properties.UserId.eq(userId)).build().unique();

        if (userBean != null) {
            Logger.t(TAG).d("用户" + userId + "randomFKey:" + userBean.getRandomGesture());
            return userBean.getRandomGesture();
        } else {
            Logger.t(TAG).d("用户不存在,id为" + userId);
            return null;
        }
    }

    public static String getFingerPrintRandomKey(String userId) {
        UserBean userBean = mUserBeanDao.queryBuilder().where(UserBeanDao.Properties.UserId.eq(userId)).build().unique();

        if (userBean != null) {
            Logger.t(TAG).d("用户" + userId + "randomFKey:" + userBean.getRandomFingerPrint());
            return userBean.getRandomFingerPrint();
        } else {
            Logger.t(TAG).d("用户不存在,id为" + userId);
            return null;
        }
    }

    /**
     * 更新指纹密码
     * @param userBean
     * @param randomFKey
     */
    public static void updateFingerPrint(UserBean userBean, String randomFKey) {
        UserBean mUserBean = mUserBeanDao.queryBuilder().where(UserBeanDao.Properties.UserId.eq(userBean.getUserId())).build().unique();

        if (mUserBean != null) {
            mUserBean.setRandomFingerPrint(randomFKey);
            mUserBean.setIsFingerPrintOpen(userBean.getIsFingerPrintOpen());
            mUserBean.setRecordIdentNumber("1");
            mUserBeanDao.update(mUserBean);//更新数据库
            Logger.t(TAG).d("数据更新成功" + mUserBean.toString());
        } else {
            Logger.t(TAG).d("用户不存在,id为" + userBean.getUserId());
        }
    }

    /**
     * 更新手势密码
     * @param userBean
     * @param randomFKey
     */
    public static void updateGesture(UserBean userBean, byte[] salt, String randomFKey) {
        UserBean mUserBean = mUserBeanDao.queryBuilder().where(UserBeanDao.Properties.UserId.eq(userBean.getUserId())).build().unique();

        if (mUserBean != null) {
            mUserBean.setGesture_salt(salt);
            mUserBean.setRandomGesture(randomFKey);
            mUserBean.setIsGestureOpen(true);
            mUserBean.setRecordIdentNumber("1");
            mUserBeanDao.update(mUserBean);//更新数据库
            Logger.t(TAG).d("数据更新成功" + mUserBean.toString());
        } else {
            Logger.t(TAG).d("用户不存在,id为" + userBean.getUserId());
        }
    }

    /**
     * 清空指纹密码
     * @param userId
     */
    public static void clearFingerPrint(String userId) {
        UserBean userBean = mUserBeanDao.queryBuilder().where(UserBeanDao.Properties.UserId.eq(userId)).build().unique();

        if (userBean != null) {
            userBean.setRandomFingerPrint(null);
            userBean.setIsFingerPrintOpen(false);
            mUserBeanDao.update(userBean);//更新数据库
            Logger.t(TAG).d("数据更新成功" + userBean.toString());
        } else {
            Logger.t(TAG).d("用户不存在,id为" + userId);
        }
    }
    /**
     * 清空手势密码
     * @param userId
     */
    public static void clearGesture(String userId) {
        UserBean userBean = mUserBeanDao.queryBuilder().where(UserBeanDao.Properties.UserId.eq(userId)).build().unique();

        if (userBean != null) {
            Logger.t(TAG).d("用户" + userId + "盐为" + userBean.getGesture_salt() + ",randomFKey:" + userBean.getRandomGesture());
            userBean.setGesture_salt(null);
            userBean.setRandomGesture(null);
            userBean.setIsGestureOpen(false);
            mUserBeanDao.update(userBean);//更新数据库
            Logger.t(TAG).d("数据更新成功" + userBean.toString());
        } else {
            Logger.t(TAG).d("用户不存在,id为" + userId);
        }
    }

    /**
     * 判断是否有登录过的用户
     *
     * @return true--有
     */
    public static boolean hasUser() {
        List<UserBean> userList = new ArrayList<>();
        try {
            userList.addAll(mUserBeanDao.queryBuilder()
                    .where(UserBeanDao.Properties.Id.notEq(-1))
                    .orderAsc(UserBeanDao.Properties.Id)
//                .limit(5)
                    .build().list());
        } catch (Exception e) {
            Logger.t(TAG).d(e);
        }

        StringBuilder string = new StringBuilder("");
        for (int i = 0; i < userList.size(); i++) {
            if("1".equals(userList.get(i).getRecordIdentNumber())) {
                string.append("\n" + userList.get(i).toString());
            }
        }
        Logger.t(TAG).d(TextUtils.isEmpty(string.toString()) ? "暂无数据" : string.toString());
        return TextUtils.isEmpty(string.toString()) ? false : true;
    }

    /**
     * 删除用户
     *
     * @param userId
     */
    public static boolean deleteUser(String userId) {
        UserBean userBean = mUserBeanDao.queryBuilder().where(UserBeanDao.Properties.UserId.eq(userId)).build().unique();

        if (userBean != null) {
            mUserBeanDao.deleteByKey(userBean.getId());
            Logger.t(TAG).d("用户" + userId + "删除成功");
            return true;
        } else {
            Logger.t(TAG).d("用户不存在,id为" + userId);
            return false;
        }
    }

    /**
     * 删除全部
     */
    public static void clearUser() {
        mUserBeanDao.deleteAll();
        Logger.t(TAG).d("清除成功");

    }

    /**
     * 判断用户是否存在
     *
     * @param userId
     * @return true--存在，false--不存在
     */
    public static boolean isUserExist(String userId) {
        UserBean userBean = mUserBeanDao.queryBuilder().where(UserBeanDao.Properties.UserId.eq(userId)).build().unique();
        return userBean != null;
    }

    public static String findUserId() {
        List<UserBean> list = new ArrayList<>();
        try {
            list.addAll(mUserBeanDao.queryBuilder()
                    .where(UserBeanDao.Properties.Id.notEq(-1))
                    .orderAsc(UserBeanDao.Properties.Id)
//                .limit(5)
                    .build().list());
        } catch (Exception e) {
            Logger.t(TAG).d(e);
        }

        if (list != null && !list.isEmpty() && list.size() > 0) {
            return list.get(0).getUserId();
        } else {
            return "";
        }
    }

    /**
     * 返回最后一次登录并且有记住证件号码的用户id
     *
     * @return
     */
    public String getLastLoginAndRecordUserId() {

        List<UserBean> list = UserBeanUtil.getInstance().findUserList();
        long lastLoginTime = 0;
        String userId = "";
        if (list != null) {
            for (UserBean bean : list) {
                if ("1".equals(bean.getRecordIdentNumber())) {
                    if (StringUtils.isNullOrEmpty(userId) || bean.getLastLoginTime() > lastLoginTime) {
                        userId = bean.getUserId();
                        lastLoginTime = bean.getLastLoginTime();
                    }
                }
            }
        }
        return userId;
    }

    /**
     * 获取最后一次登录的用户信息
     *
     * @return
     */
    public UserBean getLastLoginUserBean() {
        return UserBeanUtil.getInstance().mUserBeanDao
                .queryBuilder()
                .where(UserBeanDao.Properties.UserId.eq(getLastLoginAndRecordUserId()))
                .build().unique();

    }
}
